﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using COMOSOFT.OrderBusiness.Forms;
using System.Data.SqlClient;
using DevExpress.XtraBars.Helpers;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using System.IO;
using COMOSOFT.Class;
using COMOSOFT.OrderBusiness;
using COMOSOFT.MatarialManagement.Forms;
using COMOSOFT.JobManagement.Froms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraNavBar;
using DevExpress.XtraBars.Alerter;
using DevExpress.XtraTabbedMdi;
using System.Net.Mail;

namespace COMOSOFT.Main
{
    public partial class FrmMain : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        ClassShare cls = new ClassShare("FrmMain");
        TabGeneralView frGV = null;
        FrmFactoryPurchaseMaster frFPM = null;
        FrmStyleDetails frSD = null;
        FrmMAGeneralView frMAGV = null;
        FrmMALibrary frMALib = null;
        FrmJobManagement frJobM = null;
        FrmJobGeneral frJobGr = null;
        FrmJobStatistic frJobStatistic = null;
        FrmBAGaneralView frBaGV = null;
        FrmBookMA frBMA = null;
       
       // DataTable dtbJob;
        string _pages = null;
        object month, cid,sup;
        string Items=null;
        int JID, timejob=0,TimeAlert=0,TimeRequester=0,TimeNotAccept=0; 
        List<string> Pages = new List<string>();
        // 
        struct _Layout
        {
            public string formname;
            public string pagename;           
        }
        List<_Layout> ListLayout = new List<_Layout>();
        //---------------
        public FrmMain()
        {            
            InitializeComponent();
            DevExpress.UserSkins.BonusSkins.Register();           
            #region [Skin]
            SkinHelper.InitSkinGallery(ribbonGallery_Job);
            SkinHelper.InitSkinGallery(ribbonGallery_Orderskin);
            SkinHelper.InitSkinGallery(ribbonGallery_MASkin);
            SkinHelper.InitSkinGallery(ribbonGallery_WHSkin);
            SkinHelper.InitSkinGallery(ribbonGallery_PMSkin);
            SkinHelper.InitSkinGallery(ribbonGallery_BMSkin);
            #endregion
        }

        #region [CheckTabPage on Ribbon]
        public void CheckTabPage()
        {
            try
            {
                DataTable dtb = cls.CheckEmployee(ClassShare.Usid);
                if (dtb.Rows.Count > 0)
                {
                    for (int n = 0; n < dtb.Rows.Count; n++)
                    {
                        string tabname = dtb.Rows[n][0].ToString();
                        int num = ribbon.Pages.Count;
                        for (int i = 0; i < num; i++)
                        {
                            if (Ribbon.Pages[i].Text == tabname)
                            {
                                Ribbon.Pages[i].Visible = true;
                            }
                        }                        
                    }
                }
                this.Text = Ribbon.SelectedPage.Text;
                CheckNavbarcontrol(Ribbon.SelectedPage.Text);
            }
            catch(Exception e)
            {
                XtraMessageBox.Show(e.Message);
            }
        }
        #endregion

        #region [Clear TabbedManager]
        private void ClearTabbed()
        {
            int numpage = xtraTabbedMdiManager_TabForm.Pages.Count;
            for (int i = 0; i < numpage; i++)
            {
                xtraTabbedMdiManager_TabForm.Pages[0].MdiChild.Close();
            }
        }
        #endregion

        #region[Ribbon CLick]
        private void ribbon_Click(object sender, EventArgs e)
        {
            try
            {
                string pagename = Ribbon.SelectedPage.Text;
                SelectPage(pagename);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SelectPage(string pagename)
        {
            if (_pages != null && _pages != pagename)
            {
                this.Text = pagename;
                CheckNavbarcontrol(pagename);
                _pages = pagename;
                //ClearTabbed();                   
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
                switch (pagename)
                {
                    case "Order Management":
                        ribbonPageGroup_FtyPurChase.Visible = false;
                        ribbonPageGroup_OrderDetails.Visible = true;
                        break;
                    case "Matarial Management":
                        ribbonPageGroup_Matarial.Visible = false;
                        ribbonPageGroup_MALibrary.Visible = true;
                        break;
                    case "WareHouse Management":
                        break;
                    case "Production Management":
                        break;
                    case "Business Management":
                        break;
                }
            }
        }
        #endregion

        //Order Business
        
        #region [Refresh data]
        public void RefreshOrdermenu()
        {
            try
            {
                gridOrderMenu.DataSource = sp_OrderMenuTableAdapter.Fill(dataSetOrderManagement.sp_OrderMenu, ClassShare.Usid);
                grid_FtyPurMaster.DataSource = sp_FtyPurMasterLoadTableAdapter.Fill(dataSetOrderManagement.sp_FtyPurMasterLoad);
                frGV = ActiveMdiChild as TabGeneralView;
                frGV.RefreshData();             
            }
            catch
            {
                MessageBox.Show("Can't refresh! Please try again!");
            }
        }
        #endregion

        #region[Event Ribbon OrderDetails]
        private void OrderDetails_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "Refresh":
                    if(frFPM!=null && !frFPM.IsDisposed)
                       RefreshOrdermenu();
                    break;
                case "Save Purchase to Factory":
                    try
                    {
                        frFPM = ActiveMdiChild as FrmFactoryPurchaseMaster;
                        frFPM.UpdateFPM();
                        frFPM.LoadFPM();
                    }
                    catch
                    { 
                    }
                    break;
                default :
                    break;
            }
        }
        #endregion        

        #region [Top data]
        public void TopData()
        {
            gridOrderMenu.DataSource = sp_OrderMenuTableAdapter.Fill(dataSetOrderManagement.sp_OrderMenu, ClassShare.Usid);
        }
        #endregion

        #region [Check Navbarcontrol]
        private void CheckNavbarcontrol(string tabname)
        {
            for (int i = 0; i < navBarControl_menu.Groups.Count; i++)
            {
                navBarControl_menu.Groups[i].Visible = false;
            }
            switch (tabname)
            {
                case "Job Management":
                    navBarControl_menu.Groups["navBarGroup_JobList"].Visible = true;
                    break;
                case "Order Management":
                    navBarControl_menu.Groups["navBarGroup_General"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_Purchasing"].Visible = true;
                    break;
                case "Matarial Management":
                    navBarControl_menu.Groups["navBarGroup_Source"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_MAList"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_Booking"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_Blaning"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_Exception"].Visible = true;
                    break;
                case "WareHouse Management":
                    navBarControl_menu.Groups["navBarGroup_ImportMA"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_ImportProduct"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_ExportMA"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_ExportProduct"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_StockAndException"].Visible = true;
                    break;
                case "Production Management":
                    navBarControl_menu.Groups["navBarGroup_FollowUp"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_DeleveryPlaning"].Visible = true;
                    break;
                case "Business Management":
                    navBarControl_menu.Groups["navBarGroup_FollowUp"].Visible = true;
                    navBarControl_menu.Groups["navBarGroup_DeleveryPlaning"].Visible = true;
                    break;
            }
        }
        #endregion

        #region [Order Menu]
        private void gridViewmenu_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;

                if (view.IsGroupRow(view.FocusedRowHandle) == true)
                {
                    if (view.GetRowLevel(view.FocusedRowHandle) == 0)
                    {
                        month = null;                    
                        cid = null;
                    }
                    else if (view.GetRowLevel(view.FocusedRowHandle) == 1)
                    {
                        month = Convert.ToInt32(view.GetFocusedDataRow()["Month"]);
                        cid = null;
                    }
                }
                else
                {
                    month = Convert.ToInt32(view.GetFocusedDataRow()["Month"]);
                    cid = view.GetFocusedDataRow()["Customer"].ToString();
                }

                if (frGV != null && frGV.IsDisposed == false)
                {
                    frGV.Select();
                    frGV.LoadGV(Convert.ToInt32(view.GetFocusedDataRow()["Year"]), month,cid);
                }
                else
                {
                    frGV = new TabGeneralView(this);
                    frGV.MdiParent = this;
                    frGV.Show();
                    frGV.LoadGV(Convert.ToInt32(view.GetFocusedDataRow()["Year"]), month, cid);
                    //----------------------------
                    Savelayout(frGV.Text, ribbon.SelectedPage.Text);
                }
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;            
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Event Ribbon FtyPurChase]
        private void FtyPurChase_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "New":
                    frFPM = new FrmFactoryPurchaseMaster(-1) { MdiParent = this, Text = "PO: Add new Factory Purchase" };                   
                    frFPM.LoadFPM();                    
                    frFPM.Show();
                    frFPM.NewFPM();
                    Savelayout(frFPM.Text, ribbon.SelectedPage.Text);
                    break;
                case "Save":
                    try
                    {                        
                        frFPM = ActiveMdiChild as FrmFactoryPurchaseMaster;
                        frFPM.UpdateFPM();
                        frFPM.LoadFPM();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message + "\n Nothing to update !!!");
                    }                    
                    break;
                case "Delete":
                    if (frFPM != null && !frFPM.IsDisposed)
                    {
                        frFPM.DeleteFtyPurMaster();
                        this.sp_FtyPurMasterLoadTableAdapter.Fill(this.dataSetOrderManagement.sp_FtyPurMasterLoad);
                    }                           
                    break;
                case "Refresh":
                    if (frFPM != null && !frFPM.IsDisposed)
                    {
                        this.sp_FtyPurMasterLoadTableAdapter.Fill(this.dataSetOrderManagement.sp_FtyPurMasterLoad);
                    }
                    break;
                case "Confirm List":
                    FrmApprovingManagement frmAM = new FrmApprovingManagement();
                    frmAM.Show();
                    frmAM.MdiParent = this;
                    break;
            }
        }
        #endregion

        #region[Purchasing Menu]
        private void gridView_Purchasing_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                int fpid = Convert.ToInt32(gridView_Purchasing.GetFocusedDataRow()[0]);
                string title ="PO: "+ gridView_Purchasing.GetFocusedDataRow()["PONo"].ToString();
                ClassShare.fpid = fpid;               
                int flag=0;
                foreach(string item in Pages)
                {                   
                    if (frFPM != null && frFPM.IsDisposed == false && title == item)
                    {
                        frFPM.Select();
                        flag=1;
                        break;
                    }
                }
                if (flag == 0)
                {                    
                    frFPM = new FrmFactoryPurchaseMaster(fpid);
                    frFPM.MdiParent = this;
                    frFPM.Text = title;
                    frFPM.LoadFPM();
                    frFPM.Show();
                    Pages.Add(title);
                    Savelayout(frFPM.Text, ribbon.SelectedPage.Text);
                }                    
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }        
        }
        #endregion

        //-----------------

        #region [Form Load]
        private void FrmMain_Load(object sender, EventArgs e)
        { 
            this.sp_BookMAMenuTableAdapter.Fill(this.dataSetBalancing.sp_BookMAMenu);            
            this.sp_BAMenuTableAdapter.Fill(this.dataSetBalancing.sp_BAMenu);
            this.employeeTableAdapter.Fill(dataSet_JobManagement.Employee,ClassShare.Usid);
            DataTable dtb = dataSet_JobManagement.Employee;
            if (dtb.Rows.Count > 0)
            {
                if (dtb.Rows[0]["Image"].ToString() != null && dtb.Rows[0]["Image"].ToString() != "")
                {
                    byte[] Img = System.IO.File.ReadAllBytes(ClassShare.System_Image+@"\"+ dtb.Rows[0]["Image"].ToString());
                    picture_Image.EditValue = Img;
                }
            }

            this.sp_JobMenuTableAdapter.Fill(this.dataSet_JobManagement.sp_JobMenu, ClassShare.Usid);
            this.sp_MALibraryMenuTableAdapter.Fill(this.dataSetMatarial1.sp_MALibraryMenu);
            this.sp_MAListMasterLoadTableAdapter.Fill(this.dataSetMatarial.sp_MAListMasterLoad);
            this.sp_FtyPurMasterLoadTableAdapter.Fill(this.dataSetOrderManagement.sp_FtyPurMasterLoad);
            ribbonPageGroup_FtyPurChase.Visible = false;
            _pages = ribbon.SelectedPage.Text;
           // dtbJob = sp_JobMenuTableAdapter.GetData(ClassShare.Usid);

            // Job            
            frJobGr = new FrmJobGeneral(this) { MdiParent = this };
            frJobGr.Show();
            Savelayout(frJobGr.Text, ribbon.SelectedPage.Text);
        }
        #endregion

        //Material Management

        #region [Material Menu]
        private void gridView_MAList_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                int malid = Convert.ToInt16(gridView_MAList.GetFocusedDataRow()["MALID"]);                
                frSD = new FrmStyleDetails(malid);
                frSD.MdiParent = this;
                frSD.LoadData();
                frSD.Text = "MAPO: " + gridView_MAList.GetFocusedDataRow()["MALNo"].ToString();
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                frSD.Show();
                frSD.RunBackroundWorker();
                Savelayout(frSD.Text,"Matarial Management");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Refresh Material]
        private void RefreshMaterial()
        {
            sp_MAListMasterLoadTableAdapter.Fill(dataSetMatarial.sp_MAListMasterLoad);
        }
        #endregion

        #region [Event Ribbon Material]
        private void Matarial_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                switch (e.Item.Caption)
                {
                    case "New Material List":
                        frSD = new FrmStyleDetails(-1) { MdiParent = this, Text = "Add new Matarial" };                      
                        frSD.Show();
                        frSD.AddNew();
                        frSD.LoadData();
                        Savelayout(frSD.Text, ribbon.SelectedPage.Text);
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                        break;
                    case "Save":
                        try
                        {
                            if (frSD != null && !frSD.IsDisposed)
                            {
                                frSD.UpdateData();
                                frSD.LoadData();
                                this.sp_BAMenuTableAdapter.Fill(this.dataSetBalancing.sp_BAMenu);
                                Savelayout(frSD.Text, ribbon.SelectedPage.Text);
                            }
                        }
                        catch (Exception ex)
                        {
                             MessageBox.Show(ex.Message + "\n Nothing to update !!!");
                        }
                        break;
                      
                    case "Delete":
                        if (frSD != null && !frSD.IsDisposed)
                        {
                            frSD.DeleteMaster();
                            RefreshMaterial();
                            this.sp_BAMenuTableAdapter.Fill(this.dataSetBalancing.sp_BAMenu);
                            frSD.RunBackroundWorker();
                        }
                        break;
                    case "Refresh":                        
                        if (frSD != null && !frSD.IsDisposed)
                        {
                            RefreshMaterial();
                            frSD.RunBackroundWorker();
                        }
                        break;
                    case "Preview":
                        if (frSD != null && !frSD.IsDisposed)                        
                            frSD.Preview();                       
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Change Item Menu]

        //*********************************************************************************
        private void navBarControl_menu_Change(object sender, EventArgs e)
        {
            try
            {
                switch (navBarControl_menu.ActiveGroup.Caption)
                {
                    //OrderDetails
                    case "Job List":
                        break;
                    case "General":
                        ribbonPageGroup_OrderDetails.Visible = true;
                        ribbonPageGroup_FtyPurChase.Visible = false;
                        break;
                    case "Purchasing View":
                        ribbonPageGroup_FtyPurChase.Visible = true; ;
                        ribbonPageGroup_OrderDetails.Visible = false;
                        break;
                    //-----------------
                    //Material
                    case "Material Library":
                        ribbonPageGroup_MALibrary.Visible = true;
                        ribbonPageGroup_Matarial.Visible = false;
                        ribbonPageGroup_Booking.Visible = false;
                        ribbonPageGroup_Balance.Visible = false;
                        break;
                    case "Material List":
                        ribbonPageGroup_MALibrary.Visible = false;
                        ribbonPageGroup_Matarial.Visible = true;
                        ribbonPageGroup_Booking.Visible = false;
                        ribbonPageGroup_Balance.Visible = false;
                        break;
                    case "Booking":
                        ribbonPageGroup_MALibrary.Visible = false;
                        ribbonPageGroup_Matarial.Visible =false;
                        ribbonPageGroup_Booking.Visible = true;
                        ribbonPageGroup_Balance.Visible = false;
                        break;
                    case "Balancing":
                        ribbonPageGroup_MALibrary.Visible = false;
                        ribbonPageGroup_Matarial.Visible =false;
                        ribbonPageGroup_Booking.Visible = false;
                        ribbonPageGroup_Balance.Visible = true;
                        break;
                    //-----------------
                    default:
                        break;
                }
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
                //ClearTabbed();
            }
            catch
            {
                MessageBox.Show("Disconnect database! Connect try again");
            }
        }      
        //*************************************************************************************
        
        #endregion

        #region[MALibrary]
        private void gridView_MALibrary_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                int year = Convert.ToInt32(view.GetFocusedDataRow()["Year"]);
                if (view.IsGroupRow(view.FocusedRowHandle) == true)
                {
                    if (view.GetRowLevel(view.FocusedRowHandle) == 0)
                    {
                        sup = null;
                    }                    
                }
                else
                    sup = Convert.ToInt32(view.GetFocusedDataRow()["MASUPID"]);

                if (frMAGV != null && frMAGV.IsDisposed == false)
                {
                    frMAGV.Select();
                    frMAGV.LoadMAGV(year, sup);
                }
                else
                {
                    frMAGV = new FrmMAGeneralView(this);
                    frMAGV.MdiParent = this;
                    frMAGV.Show();
                    frMAGV.LoadMAGV(year, sup);
                    //----------------------------
                    Savelayout(frMAGV.Text, ribbon.SelectedPage.Text);
                }
               navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
            catch
            {
                MessageBox.Show("This Supplier Unused!!!","Value DBNull...",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
        }
        #endregion

        //Material Library
        #region [Update Material Libray]
        private void MALibrary_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                switch (e.Item.Caption)
                {
                    case "New":
                        frMALib = new FrmMALibrary(-1);
                        frMALib.MdiParent = this;
                        frMALib.Text = "Add new Material Library";                        
                        frMALib.Show();
                        frMALib.AddNew();
                        frMALib.LoadData();
                        navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                        break;
                    case "Save":
                        try
                        {
                            if (frMAGV != null && frMAGV.IsDisposed == false)
                            {
                                frMALib.UpdateMAL();
                                frMALib.LoadData();
                                if (frMAGV != null && frMAGV.IsDisposed == false)
                                {
                                    frMAGV.RefreshData();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message + "\n Nothing to update !!!");
                        }
                        break;
                    case "Delete":
                        if (frMAGV != null && frMAGV.IsDisposed == false)
                        {
                            frMALib.DeleteMALib();
                            sp_MALibraryMenuTableAdapter.Fill(dataSetMatarial.sp_MALibraryMenu);
                            frMALib.LoadData();
                        }
                        break;
                    case "Refresh":                        
                        sp_MALibraryMenuTableAdapter.Fill(dataSetMatarial.sp_MALibraryMenu);
                        if (frMAGV != null && frMAGV.IsDisposed == false)
                        {
                            frMAGV.RefreshData();
                        }               
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion       

        //-------------------
        //Job Management
        #region [Event Menu]
        private void gridView_JobManage_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (!view.IsGroupRow(view.FocusedRowHandle))
                {
                    JID = Convert.ToInt32(view.GetFocusedDataRow()["JID"]);
                    frJobM = new FrmJobManagement(JID, true);
                    frJobM.Show();
                    frJobM.LoadData();
                    Savelayout(frJobM.Text, ribbon.SelectedPage.Text);       
                }             
            }
            catch
            {
                MessageBox.Show("Disconnect Database! Try connect to again!", "Disconnect...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [Event Ribbon Job]
        private void JobItem_Click(object sender, ItemClickEventArgs e)
        {
            try
            {
                switch (e.Item.Caption)
                {                    
                    case "New Job":
                        frJobM = new FrmJobManagement(-1,true) { MdiParent = this, Text = "Add new Job" };
                        frJobM.Show();
                        frJobM.AddNew();
                        frJobM.LoadData();
                        frJobM.CheckButton();
                        Savelayout(frJobM.Text, ribbon.SelectedPage.Text);
                        break;
                    case "Create From Job":
                        frJobM = new FrmJobManagement(-1, false) { MdiParent = this, Text = "Add new Job" };
                        frJobM.Show();
                        frJobM.AddNew();
                        frJobM.LoadData();
                        frJobM.CheckButton();
                        Savelayout(frJobM.Text, ribbon.SelectedPage.Text);
                        break;
                    case "Send":
                        if (frJobM != null && !frJobM.IsDisposed)
                        {
                            frJobM.UpdateJob();
                            sp_JobMenuTableAdapter.Fill(dataSet_JobManagement.sp_JobMenu, ClassShare.Usid);
                            frJobGr = ActiveMdiChild as FrmJobGeneral;
                            frJobGr.LoadData();
                        }
                        //frJobM.LoadData();
                        break;
                    case "Delete":
                        break;
                    case "Refresh":
                        sp_JobMenuTableAdapter.Fill(dataSet_JobManagement.sp_JobMenu, ClassShare.Usid);
                        if (frJobGr != null && !frJobGr.IsDisposed)
                            frJobGr.LoadData();
                        break;
                    case "Job General":
                        if (frJobGr != null && !frJobGr.IsDisposed)
                            frJobGr.Select();
                        else
                        {
                            frJobGr = new FrmJobGeneral(this) { MdiParent = this };
                            frJobGr.Show();
                            frJobGr.LoadData();
                            Savelayout(frJobGr.Text, ribbon.SelectedPage.Text);
                        }
                        // navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
                        break;
                    case "Print":
                        FrmSetupReport frmJobReport = new FrmSetupReport();                        
                        frmJobReport.ShowDialog();
                        break;
                    case "Statistical":
                        if (frJobStatistic != null && !frJobStatistic.IsDisposed)
                            frJobStatistic.Select();
                        else
                        {
                            frJobStatistic = new FrmJobStatistic() { MdiParent=this};
                            frJobStatistic.Show();
                        }
                        break;                    
                }
            }
            catch
            {
                MessageBox.Show("Disconnect database! Connect try again");
            }
        }
        #endregion  

        #region [Alarms New Job]
        private void timer_job_Tick(object sender, EventArgs e)
        {
            try
            {
                timejob++;
                if (timejob == 120)
                {
                    DataTable dtb = cls.GetData("sp_JobAlertNewJob", new string[] { "@EID" }, new object[] { ClassShare.Usid });
                    for (int i = 0; i < dtb.Rows.Count; i++)
                        {
                            AlertInfo info = new AlertInfo("Job Reminder", " You have a new job '" + dtb.Rows[i]["Title"] + "'", imageCollection_Alert.Images[0]);
                            alertControl_info.Show(this, info);
                            JID = Convert.ToInt32(dtb.Rows[i]["JID"]);
                        }                  
                    timejob = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Timer]
        // Job Expired and Job Fail
        private void timer_JobRequie_Tick(object sender, EventArgs e)
        {
            TimeAlert++;
            if (TimeAlert == 240)
            {
                try
                {
                    sp_JobAlertTableAdapter.Fill(dataSet_JobManagement.sp_JobAlert, ClassShare.Usid);
                    DataTable dtbJobAlert = sp_JobAlertTableAdapter.GetData(ClassShare.Usid);
                    for (int i = 0; i < dtbJobAlert.Rows.Count; i++)
                        {
                            if (Convert.ToInt32(dtbJobAlert.Rows[i]["Hour"]) <= 300 && Convert.ToInt32(dtbJobAlert.Rows[i]["Hour"]) > 0)
                            {
                                JID = Convert.ToInt32(dtbJobAlert.Rows[i]["JID"]);
                                AlertInfo info = new AlertInfo("Job expired", "Your job '" + dtbJobAlert.Rows[i]["Title"].ToString() + "'\n Just " + dtbJobAlert.Rows[i]["Hour"].ToString() + "  munite is expired",imageCollection_Alert.Images[1]);
                                alertControl_info.Show(this, info);
                            }
                            else
                            {                              
                                if (Convert.ToInt32(dtbJobAlert.Rows[i]["Hour"]) <= 0)
                                {
                                    AlertInfo info = new AlertInfo("Job Fail", "Your job '" + dtbJobAlert.Rows[i]["Title"].ToString() + "'\n was Failed!", imageCollection_Alert.Images[2]);
                                    alertControl_info.Show(this, info);
                                    JID = Convert.ToInt32(dtbJobAlert.Rows[i]["JID"]);
                                    cls.UpdateData("sp_JobSubmiterUpdate", new string[] { "@JID", "@EID", "@Status", "@Comment", "@flag" }, new object[] { Convert.ToInt64(dtbJobAlert.Rows[i]["JID"]), ClassShare.Usid, "Failed", "Not Comment", 2 });                                                   
                                }                                
                            }
                        }                  
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                TimeAlert = 0;
            }
        }

        //
        private void timer_JobRequester_Tick(object sender, EventArgs e)
        {
            TimeRequester++;
            if (TimeRequester == 180)
            {
                try
                {
                    DataTable dtbRequester = cls.GetData("sp_JobRequester", new string[] { "@EID" }, new object[] { ClassShare.Usid });
                    for (int index = 0; index < dtbRequester.Rows.Count; index++)
                    {
                        if (Convert.ToInt16(dtbRequester.Rows[index]["Hour"]) < 2 && Convert.ToInt16(dtbRequester.Rows[index]["Hour"]) > 0)
                        {
                            AlertInfo info = new AlertInfo("Job Approval", "Your job require '" + dtbRequester.Rows[index]["Title"].ToString() + "'\n Just 1 hour is approval", imageCollection_Alert.Images[3]);
                            alertControl_info.Show(this, info);
                            JID = Convert.ToInt32(dtbRequester.Rows[index]["JID"]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                TimeRequester = 0;
            }
        }

        private void timer_NotAccept_Tick(object sender, EventArgs e)
        {
            TimeNotAccept++;
            if (TimeNotAccept == 300)
            {
                try
                {
                    DataTable dtb_notaccept = cls.GetData("sp_JobAlerNotAccept", new string[] { "@EID" }, new object[] { ClassShare.Usid });
                    for (int i = 0; i < dtb_notaccept.Rows.Count; i++)
                    {
                        AlertInfo info = new AlertInfo("Job not accept", dtb_notaccept.Rows[i]["FullName"].ToString() + " doesn't accept the job '" + dtb_notaccept.Rows[i]["Title"].ToString() + "'\n that you assign!",imageCollection_Alert.Images[4]);
                        alertControl_info.Show(this, info);
                        MailMessage message = new MailMessage();
                        SmtpClient Client = new SmtpClient();
                        Client.Host = "smtp.gmail.com";
                        Client.Port = 587;
                        Client.Credentials = new System.Net.NetworkCredential("comosoft.como@gmail.com", "@Comosoft324");
                        Client.EnableSsl = true;
                        Client.DeliveryMethod = SmtpDeliveryMethod.Network;
                        message.From = new MailAddress(ClassShare.Email);
                        message.Sender = new MailAddress(ClassShare.Email);

                        message.To.Add(new MailAddress(ClassShare.Email));
                        message.To.Add(new MailAddress(dtb_notaccept.Rows[i]["Email"].ToString()));

                        message.Subject = " COMOSOFT - Not Accept Job";
                        message.Body = "COMOSOFT Notify: " + dtb_notaccept.Rows[i]["FullName"].ToString() + " not yet accept the job '" + dtb_notaccept.Rows[i]["Title"].ToString();
                        message.IsBodyHtml = true;
                        Client.Send(message);
                        JID = Convert.ToInt32(dtb_notaccept.Rows[i]["JID"]);
                    }                   
                    TimeNotAccept = 0;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        #endregion

        #region [Click Alert]
        private void alertControl_info_AlertClick(object sender, AlertClickEventArgs e)
        {
            try
            {
                frJobM = new FrmJobManagement(JID, true);
                frJobM.Show();
                frJobM.LoadData();
                Savelayout(frJobM.Text, ribbon.SelectedPage.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        //-------------------

        //System
        #region [User Info]
        private void System_ItemClick(object sender, DevExpress.XtraBars.Ribbon.BackstageViewItemEventArgs e)
        {
            try
            {
                switch (e.Item.Caption)
                {
                    case "Login":
                        FrmLogin frmlogin = new FrmLogin();
                        frmlogin.ShowDialog();
                        this.Hide();
                        break;
                    case "Change Password":
                        FrmChangePassword frmchangepass = new FrmChangePassword();
                        frmchangepass.ShowDialog();
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [SaveLayout]
        public void Savelayout(string formname, string pagename)
        {
            _Layout Node = new _Layout();
            Node.formname = formname;
            Node.pagename = pagename;           
            ListLayout.Add(Node);
        }
        #endregion

        #region [Selecte Tabpage]
        private void xtraTabbedMdiManager_TabForm_SelectedPageChanged(object sender, EventArgs e)
        {
            try
            {
                string name = xtraTabbedMdiManager_TabForm.SelectedPage.Text;
                foreach (_Layout item in ListLayout)
                {
                    if (name == item.formname)
                    {
                        ribbon.SelectedPage =Ribbon.Pages[item.pagename];                        
                        SelectPage(item.pagename);
                    }
                }
            }
            catch
            {                
            }
        }
        #endregion      

        //BA
        #region [BA Menu]
        private void bnt_OK_Click(object sender, EventArgs e)
        {
            try
            {
                GridView view = gridView_Balancing as GridView;
                if (view.IsGroupRow(view.FocusedRowHandle) == true)
                {
                    if (view.GetRowLevel(view.FocusedRowHandle) == 0)
                    {
                        month = null;
                        Items = null;
                    }
                    if (view.GetRowLevel(view.FocusedRowHandle) == 1)
                    {
                        month = view.GetRowCellValue(view.FocusedRowHandle, "Month");
                        Items = null;
                    }
                }
                else
                {
                    month = view.GetRowCellValue(view.FocusedRowHandle, "Month");
                    int[] rows = view.GetSelectedRows();
                    foreach (int i in rows)
                        if (!view.IsGroupRow(i))
                        {
                            Items += view.GetDataRow(i)["MALID"].ToString() + ',';
                        }
                    Items = Items.Substring(0, Items.Length - 1);
                }
                frBaGV = new FrmBAGaneralView(DateTime.Now.Year, month, Items) { MdiParent = this };
                frBaGV.LoadData();
                frBaGV.Show();
                Savelayout("Balancing View", "Matarial Management");
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void gridView_BookMenu_DoubleClick(object sender, EventArgs e)
        {
            GridView view = sender as GridView;
            if (!view.IsGroupRow(view.FocusedRowHandle))
            {
                int ID = Convert.ToInt32(view.GetDataRow(view.FocusedRowHandle)["BMID"]);
                frBMA = new FrmBookMA(ID) { MdiParent = this };
                frBMA.loadData();
                frBMA.Show();
                navBarControl_menu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            }
        }
        private void BookMA_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Caption)
            {
                case "New":
                    frBMA = new FrmBookMA(-1) { MdiParent = this, Text = "Add New Book Material" };
                    frBMA.Show();
                    frBMA.AddNew();
                    break;
                case "Save":
                    if (frBMA != null && !frBMA.IsDisposed)
                    {
                        frBMA.UpdateData();
                        frBMA.loadData();
                    }
                    break;
                case "Delete":
                    if (frBMA != null && !frBMA.IsDisposed)
                    {
                        frBMA.UpdateData();
                    }
                    break;
                case "Refresh":
                    if (frBMA != null && !frBMA.IsDisposed)
                    {
                        sp_BookMAMenuTableAdapter.Fill(dataSetBalancing.sp_BookMAMenu);
                        frBMA.loadData();
                    }
                    break;
               default:
                    break;
            }
        }
         
        private void gridView_JobManage_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                string Requester = view.GetRowCellValue(e.ListSourceRowIndex, "Requester").ToString();
                string EID = view.GetRowCellValue(e.ListSourceRowIndex, "EID").ToString();
                string SubStatus = view.GetRowCellValue(e.ListSourceRowIndex, "SubStatus").ToString();
                string Status = view.GetRowCellValue(e.ListSourceRowIndex, "Status").ToString();
                if (e.Column.FieldName == "colIcon" && e.IsGetData)
                {
                    if ((Requester != EID) && SubStatus == "" && (Status == "Pending"))
                        e.Value = imageCollection_Alert.Images[5];
                    else
                        e.Value = imageCollection_Alert.Images[6];
                }
            }
            catch
            { 
            }
        }
    }
}
